<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Session;
use App\Services\CourseTypeService;
use Illuminate\Http\Request;

class CourseTypeController extends Controller{
	public function list(Request $request){
		$username = Session::get('username');

		if(!$username){
			return redirect('/admin/login'); 	
		}else{
			$ct = new CourseTypeService;
			
			$data['page_size_list'] = array(20,25,50,100);
			$data['page_size'] = $request->input('page_size') ? intval($request->input('page_size')) : 15;
			$data['keywords'] = $request->input('keywords') ? addslashes($request->input('keywords')) : '';
			$course_type_list = $ct->getCourseTypeList($data['page_size'],$data['keywords']);
			if($course_type_list !== FALSE){
				$data['ct_list'] = $course_type_list;
			}
			$data['username'] = $username;
		}

		return view('admin.coursetype.list',$data);
	}

	public function create(){
		$username = Session::get('username');

		if(!$username){
			return redirect('/admin/login');
		}else{
			$data['username'] = $username;

			$ct = new CourseTypeService;
			$data['ct_list'] = $ct->getTypeList();
		}

		return view('admin.coursetype.add',$data);
	}

	public function store(){
		date_default_timezone_set('PRC');
		$ct = new CourseTypeService;
		$data['type_name'] = addslashes($_POST['column_name']);
		$data['pid'] = intval($_POST['pid']);
		$data['add_date'] = date('Y-m-d H:i:s');
		$data['update_date'] = date('Y-m-d H:i:s');
		$data['isshow'] = 1;

		$ct_info = $ct->getCourseTypeByName($data['type_name']);

		if(!empty($ct_info)){
			$_data = array('code'=>300);
		}else{
			$res = $ct->insertCourseType($data);
			if($res){
				$_data = array('code'=>200);
			}else{
				$_data = array('code'=>400);
			}
		}

		return response()->json($_data);
	}

	public function edit($id){
		$username = Session::get('username');
		$ct = new CourseTypeService;

		if(!$username){
			return redirect('/admin/login');
		}else{
			$data['username'] = $username;
			$data['info'] = $ct->getCourseTypeById($id);
			$data['ct_list'] = $ct->getTypeList();
		}

		return view('admin.coursetype.edit',$data);
	}

	public function update(){
		$ct = new CourseTypeService;

		date_default_timezone_set('PRC');
		$id = intval($_POST['id']);
		$data['type_name'] = addslashes($_POST['column_name']);
		$data['update_date'] = date('Y-m-d H:i:s');

		$res = $ct->modifyCourseType($id,$data);
		if($res){
			$_data = array('code'=>200);
		}else{
			$_data = array('code'=>300);
		}

		return response()->json($_data);
	}

	public function del($id){
		$ct = new CourseTypeService;
		$data['isshow'] = 0;
		$res = $ct->modifyCourseType($id,$data);
		if($res){
			$_data = array('code'=>200);
		}else{
			$_data = array('code'=>400);
		}

		return response()->json($_data);
	}
}